package my;

import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Endpoint;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.soap.SOAPBinding;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServiceMain {
    public static void main(String[] args) {
        System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
        System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");

        String address = "http://0.0.0.0:8080/student";

        Endpoint endpoint = Endpoint.create(null, new ServiceImpl());

        // 正确注册Handler到服务端
        List<Handler> handlerChain = new ArrayList<>();
        handlerChain.add(new MySOAPHandler());
        endpoint.getBinding().setHandlerChain(handlerChain);

        // 可选：设置属性显式启用多个协议
        Map<String, Object> props = new HashMap<>();
        props.put("com.sun.xml.ws.binding.SOAP11", true);
        props.put("com.sun.xml.ws.binding.SOAP12", true);
        endpoint.setProperties(props);

        // 强制启用WSDL生成
        endpoint.getProperties().put(Endpoint.WSDL_SERVICE,
                new QName("http://my/", "StudentService"));
        endpoint.getProperties().put(Endpoint.WSDL_PORT,
                new QName("http://my/", "StudentPort"));

        endpoint.getProperties().put(BindingProvider.SOAPACTION_USE_PROPERTY, false);

        endpoint.publish(address);

        if (endpoint.isPublished()) {
            System.out.println("服务发布成功！");
            System.out.println("WSDL访问地址: " + address.replace("0.0.0.0", "localhost") + "?wsdl");

            // 验证服务是否真正可用
            new Thread(() -> {
                try {
                    Thread.sleep(2000);
                    System.out.println("\n=== 服务测试 ===");
                    java.net.URL url = new java.net.URL(address + "?wsdl");
                    java.io.InputStream is = url.openStream();
                    System.out.println("WSDL获取成功！");
                    is.close();
                } catch (Exception e) {
                    System.err.println("WSDL获取失败: " + e.getMessage());
                }
            }).start();
        } else {
            System.out.println("服务发布失败！");
        }
        // 添加到main方法
        System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
        System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
    }
}